package App.OO.ClientView;

import App.Model.ArisuClientDB;
import App.Model.Interface.MessageType;
import App.Model.Tool.DosTool;
import App.Model.Tool.SwingUtil;
import App.Model.User;
import App.Model.message.Message;
import App.OO.service.thread.Manage.ManageCtoSThread;
import com.alibaba.fastjson.JSON;

import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import javax.swing.plaf.basic.BasicButtonUI;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import java.text.SimpleDateFormat;

public class OOUserFrame extends JFrame {
    private final User original = new User();
    ImageIcon headerImage = null;
    String headerUrl = null;//储存更改后的图像的地址,方便传给服务器更换
    boolean isChanged_header = false;

    public void ShowUserFrame(User user,String userId){//userId为操控者,用于在线程池中获取线程socket
        if(user == null)
            return;
        original.setHeaderUrl(user.getHeaderUrl());
        original.setUserName(user.getUserName());
        original.setPassword(user.getPassword());
        original.setUserSignature(user.getUserSignature());
        Font textFont = new Font("微软雅黑", Font.BOLD, 14);
        setTitle(" " + user.getUserId() + " 的个人主页");
        setBounds(450, 350, 300, 450);    //设置窗体显示位置和大小
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        //setResizable(false);
        setBackground(new Color(194, 175, 120));//背景灰色
        //程序icon标
        setIconImage(new ImageIcon("src\\main\\resources\\recourse\\OO.png").getImage());

        //布局组件
        JButton jHeaderBtn = new JButton();//编辑头像的按钮
        JButton jEditorBtn = new JButton();//编辑用户名的按钮
        JButton jPwdBtn = new JButton();//编辑用户密码的按钮
        JButton jSignBtn = new JButton();//编辑个性签名的按钮
        ImageIcon editImage = SwingUtil.createAutoAdjustIcon
                ("src\\main\\resources\\recourse\\editor.png", true);

        //用户头像与编辑按钮
        //从数据库中获取头像,如果没有,则使用默认头像
        //headerImage = ArisuClientDB.getUserHeaderAtFile(user.getUserId());
        headerImage = ArisuClientDB.getHeaderImg(user.getUserId()) ;
        if(headerImage == null){
            headerImage = SwingUtil.createAutoAdjustIcon
                    ("src\\main\\resources\\recourse\\header\\header_null.png", true);//实例化ImageIcon 对象
        }else{
            headerImage = SwingUtil.createAutoAdjustIcon(headerImage.getImage(),true);
        }
        JLabel jHeader = new JLabel(headerImage);
        jHeader.setPreferredSize(new Dimension(70,70));
        jHeader.setBorder(BorderFactory.createLineBorder(Color.gray, 2));
        JPanel jHeaderPanel = new JPanel(new FlowLayout());
        jHeaderPanel.add(jHeader);
        if(userId.equals(user.getUserId())){
            jHeaderBtn = new JButton(editImage);
            jHeaderBtn.setUI(new BasicButtonUI());
            jHeaderBtn.setPreferredSize(new Dimension(20,20));
            jHeaderPanel.add(jHeaderBtn);
        }
            //用户称呼name与编辑箭头
        System.out.println("当前用户用户名: " + user.getUserName());
        JTextField jHText = new JTextField(user.getUserName());
        jHText.setEditable(false);
        jHText.setFont(textFont);
        JPanel jHTextPanel = new JPanel();
        jHTextPanel.add(jHText);
        if(userId.equals(user.getUserId())){
            jEditorBtn = new JButton(editImage);
            jEditorBtn.setUI(new BasicButtonUI());
            jEditorBtn.setPreferredSize(new Dimension(20,20));
            jHTextPanel.add(jEditorBtn);
        }
            //用户的注册日期
        JPanel jDatePanel = new JPanel(new FlowLayout());
        JLabel jDateText = new JLabel("注册日期: ");
        JLabel jDate = new JLabel();
        if(user.getSignDate()!= null){
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String formattedDate = formatter.format(user.getSignDate());
            jDate.setText(formattedDate);
        }else{
            jDate.setText("内测用户");
        }
        jDateText.setFont(textFont);
        jDatePanel.add(jDateText);
        jDatePanel.add(jDate);
            //用户的账号
        JPanel jIdPanel = new JPanel(new FlowLayout());
        JLabel jId = new JLabel();
        jId.setText("账号: " + user.getUserId());
        jId.setFont(textFont);
        jIdPanel.add(jId);
            //用户的密码
        JPanel jPswPanel = new JPanel(new FlowLayout());
        JLabel jPswHeader = new JLabel("密码: ");
        jPswHeader.setFont(textFont);
        JPasswordField jPwd = new JPasswordField();
        jPwd.setEchoChar('●');
        jPwd.setEditable(false);
        jPwd.setText(user.getPassword());
        jPwd.setFont(textFont);
        jPswPanel.add(jPswHeader);
        jPswPanel.add(jPwd);
        if(userId.equals(user.getUserId())){
            jPwdBtn = new JButton(editImage);
            jPwdBtn.setUI(new BasicButtonUI());
            jPwdBtn.setPreferredSize(new Dimension(20,20));
            jPswPanel.add(jPwdBtn);
        }
            //用户个性签名
        JPanel jSignaturePanel = new JPanel(new FlowLayout());
        JLabel jSign = new JLabel("个性签名: ");
        JTextArea jSignature = new JTextArea(3,40);
        jSignature.setFont(new Font("宋体",Font.BOLD,11));
        jSignature.setLineWrap(true);
        jSignature.setEditable(false);
        if(user.getUserSignature() == null){
            jSignature.setText("我不喜欢个人简介");
        }else{
            jSignature.setText(user.getUserSignature());
        }
        jSignature.setBackground(new Color(245, 245, 245));
        jSignature.setBorder(BorderFactory.createLineBorder(Color.gray, 2));
        jSignaturePanel.add(jSign);
        if(userId.equals(user.getUserId())){
            jSignBtn = new JButton(editImage);
            jSignBtn.setUI(new BasicButtonUI());
            jSignBtn.setPreferredSize(new Dimension(20,20));
            jSignaturePanel.add(jSignBtn);
        }
        jSignaturePanel.add(jSignature);

            //最底部的确认更改
        Font littleFont = new Font("宋体",Font.BOLD,13);
        JPanel jConfigPanel = new JPanel(new FlowLayout());
        JButton jConBtn = new JButton("更改");
        JButton jNotBtn = new JButton("取消");
        JLabel configLabel = new JLabel("是否更改?");
        jConBtn.setFont(littleFont);
        jNotBtn.setFont(littleFont);
        configLabel.setFont(littleFont);
        jConfigPanel.add(configLabel);
        jConfigPanel.add(jConBtn);
        jConfigPanel.add(jNotBtn);
        jConfigPanel.setVisible(false);

        Box mainBox = Box.createVerticalBox();
        mainBox.setAlignmentX(Component.CENTER_ALIGNMENT);
        mainBox.add(Box.createVerticalStrut(10));
        mainBox.add(jHeaderPanel);//头像
        //mainBox.add(Box.createVerticalStrut(10));
        mainBox.add(jHTextPanel);//用户名
        //mainBox.add(Box.createVerticalStrut(7));
        mainBox.add(jSignaturePanel);//个性签名
        //mainBox.add(Box.createVerticalStrut(7));
        mainBox.add(jDatePanel);//注册日期
        //mainBox.add(Box.createVerticalStrut(7));
        mainBox.add(jIdPanel);//用户Id
        //mainBox.add(Box.createVerticalStrut(7));
        mainBox.add(jPswPanel);//用户密码
        //mainBox.add(Box.createVerticalStrut(7));
        mainBox.add(jConfigPanel);//更改确认

        //添加布局组件
        setBackground(new Color(245, 245, 245));
        //mainBox.setBackground(new Color(200, 220, 255));
        add(mainBox);
        setVisible(true);
        repaint();

        //设置背景图片(无法运行)
//        // 设置背景
//        JLabel lblBackground = new JLabel(); // 创建一个标签组件对象
//        ImageIcon icon = SwingUtil.createAutoAdjustIcon("src\\main\\resources\\recourse\\login_bg.png",true);
//        lblBackground.setIcon(icon); // 设置标签组件要显示的图标
//        lblBackground.setBounds(0, 0, icon.getIconWidth(), icon.getIconHeight()); // 设置组件的显示位置及大小
//        getContentPane().add(lblBackground); // 将组件添加到面板中
//        lblBackground.setOpaque(false);
//        repaint();
        //事件处理
        jHeader.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                //ImageIcon detailImg = ArisuClientDB.getUserHeaderAtFile(user.getUserId());
                ImageIcon detailImg = headerImage;
                if(detailImg == null){
                    return;
                }
                JFrame frame = new JFrame();
                frame.setBounds(100, 100, detailImg.getIconWidth(), detailImg.getIconHeight());
                frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                frame.setIconImage(new ImageIcon("src\\main\\resources\\recourse\\OO.png").getImage());
                frame.setTitle("图片浏览");
                JLabel jRealImg = new JLabel(detailImg);
                frame.add(jRealImg);
                frame.setVisible(true);
            }
        });

        //编辑头像的按钮
        jHeaderBtn.addActionListener(e -> {
            FileSystemView fsv = FileSystemView.getFileSystemView();
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setAcceptAllFileFilterUsed(false);
            fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
            fileChooser.addChoosableFileFilter(
                    new javax.swing.filechooser.FileNameExtensionFilter
                            ("Images", "jpg", "png", "gif", "bmp"));
            int result = fileChooser.showOpenDialog(null);
            if(result == JFileChooser.APPROVE_OPTION) {
                isChanged_header = true;
                //String filename = fileChooser.getSelectedFile().getName();
                String src = fileChooser.getSelectedFile().getAbsolutePath();//文件路径
                headerUrl = src;
                String fileType = DosTool.GetFileType(src);
                long fileLength = fileChooser.getSelectedFile().length();
                //String fileLengthStr = DosTool.swapFileLength(fileLength);
                if(fileLength > 5242880){
                    JOptionPane.showMessageDialog(null,
                            "头像图片不得超过5mb", "警告", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                headerImage = SwingUtil.createAutoAdjustIcon(src,true);
                user.setHeaderUrl(fileType);//头像文件的图片格式,
                jHeader.setIcon(headerImage);
                jHeader.repaint();
                //System.out.println(filename + "   " + src + "   " + fileLengthStr);
            }

            jConfigPanel.setVisible(true);
        });
        //编辑用户名的按钮
        jEditorBtn.addActionListener(e -> {
            jHText.requestFocusInWindow(); // 请求焦点
            jHText.setEditable(true);
            jHText.setBackground(Color.lightGray);
            jConfigPanel.setVisible(true);
        });
        //编辑用户密码的按钮
        jPwdBtn.addActionListener(e -> {
            jPwd.requestFocusInWindow(); // 请求焦点
            jPwd.setEchoChar((char) 0);
            jPwd.setEditable(true);
            jPwd.setBackground(Color.LIGHT_GRAY);
            jConfigPanel.setVisible(true);
        });
        //编辑个性签名的按钮
        jSignBtn.addActionListener(e -> {
            jSignature.requestFocusInWindow(); // 请求焦点
            jSignature.setEditable(true);
            jSignature.setBackground(Color.lightGray);
            jConfigPanel.setVisible(true);
        });
        //确认消息更改按钮
        jConBtn.addActionListener(e -> {
            //未进行消息验证,容易增加服务器负担
            user.setUserName(jHText.getText());
            user.setUserSignature(jSignature.getText());
            user.setPassword(new String(jPwd.getPassword()));
            //user.setHeaderUrl();//未完成,传输头像文件思路未完成
            String jsonUser = JSON.toJSONString(user);

            //打包Message
            Message message = new Message();
            message.setSender(userId);
            message.setContent(jsonUser);
            message.setGetter("服务器");
            message.setMesType(MessageType.MESSAGE_SET_MSG_USER);

            //头像的图片数据保存到message的文件模块中
            if(isChanged_header){
                message.setDest("1");
                FileInputStream fileInputStream = null;
                byte[] fileBytes = new byte[(int) new File(headerUrl).length()];

                try {
                    fileInputStream = new FileInputStream(headerUrl);
                    fileInputStream.read(fileBytes);//将文件读取到fileBytes上去
                    //包装完成message
                    message.setFileBytes(fileBytes);
                } catch (Exception e1) {
                    e1.printStackTrace();
                } finally {
                    if (fileInputStream != null){
                        try {
                            fileInputStream.close();
                        } catch (IOException e2) {
                            e2.printStackTrace();
                        }
                    }
                }
                //文件发送完成后自己的数据据库中也应该保存
                ArisuClientDB.saveUserHeaderToFile(fileBytes,user.getHeaderUrl(),userId);
                //headerImage = SwingUtil.createAutoAdjustIcon(headerUrl,true);
            }
            //发送message到服务器
            try {
                ObjectOutputStream oos =
                        new ObjectOutputStream((ManageCtoSThread.getCtoSThread(userId)).getSocket().getOutputStream());
                oos.writeObject(message);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            jConfigPanel.setVisible(false);
            jHText.setEditable(false);
            jSignature.setEditable(false);
            jPwd.setEditable(false);
        });
        //取消消息更改按钮
        jNotBtn.addActionListener(e -> {
            //还有头像的转移
            isChanged_header = false;
            headerUrl = null;
            jHText.setBackground(Color.white);
            jSignature.setBackground(Color.white);
            jPwd.setBackground(Color.white);
            jHText.setText(original.getUserName());
            jSignature.setText(original.getUserSignature() == null?"我不喜欢个人简介":original.getUserSignature());
            jPwd.setText(original.getPassword());
            jPwd.setEchoChar('●');
            jConfigPanel.setVisible(false);
        });
    }

    public void ShowUserFramePlus(User user,String userId) {//plus使用GridBagLayout,视觉效果更好
    }

}
